package handler

import (
	"encoding/json"
	"filestore-server/meta"
	"filestore-server/util"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"strconv"
	"time"
)

func UploadHandler(w http.ResponseWriter,r *http.Request){
	if r.Method == "GET"{
		//返回上传html页面
		data,err := ioutil.ReadFile("./src/filestore-server/static/view/index.html")
		if err != nil{
			io.WriteString(w,"internel server error："+err.Error())
			return
		}
		io.WriteString(w,string(data))
	}else if r.Method == "POST"{
		//接受用户上传的文件流
		file,header,err := r.FormFile("file")
		if err != nil{
			io.WriteString(w,"Failed to get data,err："+err.Error())
			return
		}
		defer file.Close()

		fileMeta := meta.FileMeta{
			FileName:header.Filename,
			Location:"./src/filestore-server/tmp/"+header.Filename,
			UploadAt:time.Now().Format("2006-01-02 15:04:05"),
		}

		newFile,err := os.Create(fileMeta.Location)
		if err != nil{
			io.WriteString(w,"Failed to create file,err："+err.Error())
			return
		}
		defer newFile.Close()
		fileMeta.FileSize,err = io.Copy(newFile,file)
		if err != nil{
			io.WriteString(w,"Failed to save data into file,er："+err.Error())
			return
		}
		newFile.Seek(0,0)
		fileMeta.FileSha1 = util.FileSha1(newFile)
		meta.UpdateFileMeta(fileMeta)
		http.Redirect(w,r,"/file/upload/suc",http.StatusFound)

	}
}

func UploadSucHandler(w http.ResponseWriter,r *http.Request){
	io.WriteString(w,"Upload finished!")
}

//GetFileMetaHandler  获取文件元信息
func GetFileMetaHandler(w http.ResponseWriter,r *http.Request){
	r.ParseForm()
	filehash := r.Form["filehash"][0]
	fMeta := meta.GetFileMeta(filehash)
	data,err := json.Marshal(fMeta)
	if err != nil{
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	w.Write(data)
}

//FileQueryHandler  文件查询
func FileQueryHandler(w http.ResponseWriter,r *http.Request){
	r.ParseForm()
	limitCnt,_ := strconv.Atoi(r.Form.Get("limit"))
	fileMetas := meta.GetLastFileMetas(limitCnt)
	data,err := json.Marshal(fileMetas)
	if err != nil{
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	w.Write(data)
}

//DownloadHandler  文件下载
func DownloadHandler(w http.ResponseWriter,r *http.Request){
	r.ParseForm()
	fsha1 := r.Form.Get("filehash")

	fm := meta.GetFileMeta(fsha1)
	f,err := os.Open(fm.Location)
	if err != nil{
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	defer f.Close()

	data,err := ioutil.ReadAll(f)
	if err != nil{
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type","application/octect-stream")
	w.Header().Set("Content-disposition","attachment;filename=\""+fm.FileName+"\"")
	w.Write(data)

}

func FileMetaUpdateHandler(w http.ResponseWriter,r *http.Request){
	r.ParseForm()
	opType := r.Form.Get("op")
	fileSha1 := r.Form.Get("filehash")
	newFileName := r.Form.Get("filename")

	if opType != "0"{
		w.WriteHeader(http.StatusForbidden)
		return
	}

	if r.Method != "POST"{
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}
	
	curFileMeta := meta.GetFileMeta(fileSha1)

	curFileMeta.FileName = newFileName
	meta.UpdateFileMeta(curFileMeta)

	w.WriteHeader(http.StatusOK)

	data,err := json.Marshal(curFileMeta)
	if err != nil{
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	w.Write(data)

}


